<template>
  <a-modal
    title='操作'
    style='top: 20px;'
    :width='800'
    v-model='visible'
    :confirmLoading='confirmLoading'
    @ok='handleSubmit'
  >
    <a-form :form='form'>
      <a-form-item style='display:none'>
        <a-input v-decorator="['id']" />
      </a-form-item>
      <a-form-item style='display:none'>
        <a-input v-decorator="['version']" />
      </a-form-item>


      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属地区'>
        <a-select v-decorator="['tenantId', {rules: [{ required: true, message: '请选择所属地区' }]}]"
                  @change='selectTenant'
                  :disabled='tenantEnable'>
          <a-select-option v-for='item in tenantList' :key='item.id'>{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属园区'>
        <a-select v-decorator="['parkId', {rules: [{ required: true, message: '请选择所属园区' }]}]"
                  @change='selectPark'
                  :disabled='parkEnable'>
          <a-select-option v-for='item in parkList' :key='item.id'>{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='名称'>
        <a-input placeholder='名称' v-decorator="['name' ,{rules: [{required: true, message: '请输入名称'}]}]" />
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='品牌'>
        <a-input placeholder='品牌' v-decorator="['brand', {rules: [{required: true, message: '请输入品牌'}]}]" />
      </a-form-item>
      <!--      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="规格">-->
      <!--        <a-input placeholder="规格" v-decorator="['specification']"/>-->
      <!--      </a-form-item>-->
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='图片url'>
        <!--        <a-input placeholder="图片url" v-decorator="['picUrl']"/>-->
        <a-upload
          v-decorator="['picUrl', {rules: [{required: true, message: '请输入图片url'}]}]"
          list-type='picture-card'
          class='avatar-uploader'
          :show-upload-list='false'
          :action='uploadUrl'
          :headers='headers'
          :before-upload='beforeUpload'
          @change='handleChange'
        >
          <img v-if='imageUrl' :src='imageUrl' style='width: 102px; height: 102px' />
          <div v-else>
            <a-icon :type="loading ? 'loading' : 'plus'" />
            <div class='ant-upload-text'> 上传</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='备注'>
        <a-input placeholder='备注' v-decorator="['remark']" />
      </a-form-item>

    </a-form>
  </a-modal>
</template>
<script>
import { saveRoomItem } from '@/api/admin/meeting/roomItem'
import pick from 'lodash.pick'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getTenantList } from '@/api/tenant'
import { getParkList } from '@/api/admin/park'
import { getInfo } from '@/api/login'

export default {
  name: 'RoomItemModal',
  props: {},
  components: {},
  data() {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      uploadUrl: process.env.VUE_APP_API_BASE_URL + '/api/dfs/upload',
      headers: {
        Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN)
      },
      imageUrl: '',
      imageUrl1: '',
      loading: false,
      loading1: false,
      confirmLoading: false,
      mdl: {},
      form: this.$form.createForm(this),
      userDetail: {},
      tenantList: [], // 地区
      parkList: [], // 园区
      buildingList: [], // 楼宇
      buildingDetailList: [], // 楼层
      roomList: [], // 房间
      tenantEnable: false,
      parkEnable: false
    }
  },
  beforeCreate() {
  },
  created() {
  },
  methods: {
    // 获取用户详细信息
    getUserDetail() {
      getInfo().then(res => {
        console.log('getUserDetail', res)
        this.userDetail = res
        // 园区：5
        if (this.userDetail.roleIds && this.userDetail.roleIds.length > 0 && this.userDetail.roleIds[0] == 5) {
          //
          // 判断：是新增就查询园区
          let { id } = this.mdl
          if (!id) {
            // 选择地区 -> 查询园区
            this.selectTenant(this.userDetail.tenantId)
            // 选择园区 -> 查询楼宇
            this.selectPark(this.userDetail.parkId)
          }
          //
          // 不可编辑
          this.tenantEnable = true
          this.parkEnable = true
          // 关联地区和园区
          this.mdl.parkId = this.userDetail.parkId
          this.mdl.tenantId = this.userDetail.tenantId
          this.form.setFieldsValue({
            parkId: this.mdl.parkId,
            tenantId: this.mdl.tenantId
          })
        }
      })
    },
    // 查询地区
    getTenantData() {
      getTenantList().then(res => {
        this.tenantList = res.rows
      })
    },
    // 选择地区 -> 查询园区
    selectTenant(id) {
      console.log('selectTenant', id)
      // 清空数据
      this.mdl.parkId = null // 园区
      this.mdl.buildingId = null // 楼宇
      this.mdl.buildId = null // 楼层
      this.mdl.roomId = null // 所属房间

      this.form.setFieldsValue({
        parkId: null, // 园区

      })
      // 查询园区
      getParkList({
        tenantId: id
      }).then(res => {
        this.parkList = res.rows
      })
    },
    // 选择园区 -> 查询楼宇
    selectPark(id) {
      // 清空数据
      this.mdl.buildingId = null // 楼宇
      this.mdl.buildId = null // 楼层
      this.mdl.roomId = null // 所属房间

      this.form.setFieldsValue({
        buildingId: null, // 楼宇
        buildId: null, // 楼层
        roomId: null // 所属房间
      })
      // 查询楼宇
      this.parkId = id
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 < 500
      if (!isLt2M) {
        this.$message.error('图片必须小于 500kb!')
      }
      return isJpgOrPng && isLt2M
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        const { form: { setFieldsValue } } = this
        const result = info.file.response
        // 设置值
        this.$nextTick(() => {
          setFieldsValue({
            // 设置相对路径
            picUrl: result.fileName
          })
        })
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl
          this.loading = false
        })
      }
    },

    add() {
      this.form.resetFields()
      this.edit({ id: 0 })
    },
    edit(record) {
      this.getTenantData()
      this.mdl = Object.assign(record)
      if (this.mdl.picUrl) {
        this.imageUrl = process.env.VUE_APP_API_BASE_URL + this.mdl.picUrl
      }
      let copyMdl = JSON.parse(JSON.stringify(this.mdl))

      this.getTenantData()
      //
      if (record.id != 0) { // 编辑
        // 选择地区 -> 查询园区
        if (copyMdl.tenantId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.selectTenant(copyMdl.tenantId)
        }
        // 选择园区 -> 查询楼宇
        if (copyMdl.parkId) {
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.selectPark(copyMdl.parkId)
        }
      }
      this.getUserDetail()
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'id', 'name', 'brand', 'specification', 'picUrl', 'fileUrl', 'remark',
          'delFlag', 'createBy', 'createTime', 'updateBy', 'updateTime','tenantId', 'parkId',))
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          this.confirmLoading = true
          saveRoomItem(values).then(res => {
            if (res.code === 0) {
              this.$message.success('保存成功')
              this.$emit('ok')
              this.visible = false
            } else {
              this.$message.error(res.msg)
            }
          }).catch(() => {
            this.$message.error('系统错误，请稍后再试')
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}

function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
</script>
